package com.example.weather_forecast;


import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

/**
 * 用于处理Android 13及以上版本的通知权限请求
 */
public class NotificationPermissionHelper {

    private static final int NOTIFICATION_PERMISSION_REQUEST_CODE = 123;

    /**
     * 检查应用是否有发送通知的权限
     *
     * @param context 应用上下文
     * @return 如果有权限则返回true，否则返回false
     */
    public static boolean hasNotificationPermission(Context context) {
        // Android 13 (API级别33)及以上需要明确请求通知权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            return ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS)
                    == PackageManager.PERMISSION_GRANTED;
        }
        // 低于Android 13的版本默认已有权限
        return true;
    }

    /**
     * 请求通知权限
     *
     * @param activity 当前活动
     */
    public static void requestNotificationPermission(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ActivityCompat.requestPermissions(
                    activity,
                    new String[]{Manifest.permission.POST_NOTIFICATIONS},
                    NOTIFICATION_PERMISSION_REQUEST_CODE
            );
        }
    }

    /**
     * 处理权限请求结果
     *
     * @param requestCode  请求代码
     * @param permissions  请求的权限
     * @param grantResults 授权结果
     * @return 如果处理的是通知权限请求并且权限已被授予则返回true，否则返回false
     */
    public static boolean handlePermissionResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == NOTIFICATION_PERMISSION_REQUEST_CODE) {
            return grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;
        }
        return false;
    }
}